package logic

import (
	"cart_srv/cartsrv"
	"cart_srv/internal/svc"
	"cart_srv/models/mysql"
	"cart_srv/models/redis"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddGoodsLogic {
	return &AddGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddGoodsLogic) AddGoods(in *cartsrv.AddGoodsRequest) (*cartsrv.AddGoodsResponse, error) {
	// todo: add your logic here and delete this line

	good := mysql.Good{
		Title: in.Title,
		Cover: in.Cover,
		Price: float64(in.Price),
		Stock: int(in.Stock),
	}
	err := good.AddGoods()
	if err != nil {
		logx.Error("商品添加失败")
		return nil, fmt.Errorf("商品添加失败")
	}
	redis.SyncGoodsStock(int(good.ID), good.Stock)
	return &cartsrv.AddGoodsResponse{Id: int64(good.ID)}, nil
}
